package com.transaction.factory;

import com.transaction.SpringTransactionStatusAdaptor;
import org.apache.ibatis.session.TransactionIsolationLevel;
import org.apache.ibatis.transaction.Transaction;
import org.apache.ibatis.transaction.TransactionFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

import javax.sql.DataSource;
import java.sql.Connection;

import static org.springframework.transaction.TransactionDefinition.*;

public class SpringManagedTransactionFactoryAdaptor implements TransactionFactory {

    private final PlatformTransactionManager transactionManager;

    public SpringManagedTransactionFactoryAdaptor(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Override
    public Transaction newTransaction(Connection conn) {
        throw new UnsupportedOperationException("spring管理的事务只支持由 DataSource 创建");
    }

    @Override
    public Transaction newTransaction(DataSource dataSource, TransactionIsolationLevel level, boolean autoCommit) {

        DefaultTransactionAttribute transactionAttribute = new DefaultTransactionAttribute();

        transactionAttribute.setTimeout(3);

        int isolationLevel = ISOLATION_DEFAULT;

        if (level != null) {
            switch (level) {
                case READ_COMMITTED:
                    isolationLevel = ISOLATION_READ_COMMITTED;
                    break;
                case READ_UNCOMMITTED:
                    isolationLevel = ISOLATION_READ_UNCOMMITTED;
                    break;
                case REPEATABLE_READ:
                    isolationLevel = ISOLATION_REPEATABLE_READ;
                    break;
                case SERIALIZABLE:
                    isolationLevel = ISOLATION_SERIALIZABLE;
                    break;
            }
        }


        transactionAttribute.setIsolationLevel(isolationLevel);


        TransactionStatus transactionStatus = transactionManager.getTransaction(transactionAttribute);

        return new SpringTransactionStatusAdaptor(transactionManager,transactionStatus, dataSource, transactionAttribute.getTimeout());

    }
}
